package com.tianyalei.wolf.sample.imageload;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.tianyalei.wolf.sample.R;
import com.tianyalei.wolf.sample.application.MyApplication;

/**
 * 图片加载类，在使用前需要在application里调用initImageLoader进行初始化操作
 */
public class ImageLoadProxy {

    /**
     * 使用fresco加载图片，适用于大部分情况，需要指定图片的宽高
     * <p>
     * <com.facebook.drawee.view.SimpleDraweeView
     * android:id="@+id/my_image_view"
     * android:layout_width="20dp"
     * android:layout_height="20dp"
     * fresco:fadeDuration="300"                        //动画时长
     * fresco:actualImageScaleType="focusCrop"          //
     * fresco:placeholderImage="@color/wait_color"      //占位图
     * fresco:placeholderImageScaleType="fitCenter"     //占位图的对齐方式
     * fresco:failureImage="@drawable/error"            //失败时图片
     * fresco:failureImageScaleType="centerInside"      //失败时图片的对齐方式
     * fresco:retryImage="@drawable/retrying"           //重试时的图片
     * fresco:retryImageScaleType="centerCrop"          //重试时的图片对齐方式
     * fresco:progressBarImage="@drawable/progress_bar"
     * fresco:progressBarImageScaleType="centerInside"
     * fresco:progressBarAutoRotateInterval="1000"
     * fresco:backgroundImage="@color/blue"
     * fresco:overlayImage="@drawable/watermark"
     * fresco:pressedStateOverlayImage="@color/red"     //按压时的叠加图
     * fresco:roundAsCircle="false"                     //圆形图片
     * fresco:roundedCornerRadius="1dp"                 //圆角图片
     * fresco:roundTopLeft="true"
     * fresco:roundTopRight="false"
     * fresco:roundBottomLeft="false"
     * fresco:roundBottomRight="true"
     * fresco:roundWithOverlayColor="@color/corner_color"
     * fresco:roundingBorderWidth="2dp"
     * fresco:roundingBorderColor="@color/border_color"
     * fresco:viewAspectRatio="1.33"                    //宽高比（如果写wrap_content的话就需要指明宽高比了）
     * />
     * </p>
     *
     * @param url
     * @param target
     */
    public static void displayImage(String url, SimpleDraweeView target) {
        if (!isGif(url)) {
            Uri uri = Uri.parse(url);
            target.setImageURI(uri);
        } else {
            //展示gif
            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setUri(Uri.parse(url))
                    .setAutoPlayAnimations(true)
                    .build();
            target.setController(controller);
        }
    }

    /**
     * 展示带指定默认图的图片
     *
     * @param url
     * @param target
     * @param defaultImage
     */
    public static void displayImage(String url, SimpleDraweeView target, int defaultImage) {
        if (defaultImage == 0) {
            defaultImage = R.drawable.pictures_no;
        }
        target = generateParam(target, defaultImage);
        displayImage(url, target);
    }

    /**
     * 展示带默认图和按压图的图片
     *
     * @param url
     * @param target
     * @param defaultImage
     * @param pressImage
     */
    public static void displayImageWithPressImage(String url, SimpleDraweeView target, int defaultImage, int pressImage) {
        if (defaultImage == 0) {
            defaultImage = R.drawable.pictures_no;
        }
        if (pressImage == 0) {
            pressImage = R.drawable.shape_refresh_bg;
        }
        target = generateParam(target, defaultImage, pressImage);
        displayImage(url, target);
    }

    /**
     * 生成带默认图的
     *
     * @param target
     * @param defaultImage
     * @return
     */
    private static SimpleDraweeView generateParam(SimpleDraweeView target, int defaultImage) {
        GenericDraweeHierarchyBuilder builder =
                new GenericDraweeHierarchyBuilder(MyApplication.getInstance().getResources());
        GenericDraweeHierarchy hierarchy = builder
                .setFadeDuration(300)
                .setPlaceholderImage(MyApplication.getInstance().getResources().getDrawable(defaultImage))
                .build();

        target.setHierarchy(hierarchy);
        return target;
    }

    /**
     * 生成带默认图和点击图的
     *
     * @param target
     * @param defaultImage
     * @param pressImage
     * @return
     */
    private static SimpleDraweeView generateParam(SimpleDraweeView target, int defaultImage, int pressImage) {
        GenericDraweeHierarchyBuilder builder =
                new GenericDraweeHierarchyBuilder(MyApplication.getInstance().getResources());
        GenericDraweeHierarchy hierarchy = builder
                .setFadeDuration(300)
                .setPlaceholderImage(MyApplication.getInstance().getResources().getDrawable(defaultImage))
                .setPressedStateOverlay(MyApplication.getInstance().getResources().getDrawable(pressImage))
                .build();

        target.setHierarchy(hierarchy);
        return target;
    }

    /**
     * 展示普通的图片，不需要做裁剪和对齐方式的
     *
     * @param context
     * @param url
     * @param target
     */
    public static void displayNormalImage(Context context, String url, ImageView target) {
        if (isGif(url)) {
            displayGif(context, url, target);
            return;
        }
        Glide.with(context).load(url).crossFade().into(target);
    }

    /**
     * 展示普通的图片，不需要做裁剪和对齐方式的
     *
     * @param context
     * @param url
     * @param target
     */
    public static void displayCenterCropImage(Context context, String url, ImageView target) {
        Glide.with(context).load(url).placeholder(R.drawable.pictures_no).centerCrop().crossFade().into(target);
    }

    /**
     * 展示圆形图片
     *
     * @param context
     * @param url
     * @param target
     */
    public static void displayCircleImage(final Context context, String url, final ImageView target) {
        Glide.with(context).load(url).asBitmap().centerCrop().into(new BitmapImageViewTarget(target) {
            @Override
            protected void setResource(Bitmap resource) {
                RoundedBitmapDrawable circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                circularBitmapDrawable.setCircular(true);
                target.setImageDrawable(circularBitmapDrawable);
            }
        });
    }

    /**
     * 用glide展示gif
     *
     * @param context
     * @param url
     * @param target
     */
    public static void displayGif(Context context, String url, ImageView target) {
        Glide.with(context).load(url).asGif().placeholder(R.drawable.pictures_no).diskCacheStrategy(DiskCacheStrategy.SOURCE).crossFade().into(target);
    }

    /**
     * 判断是否是gif
     *
     * @param url
     * @return
     */
    private static boolean isGif(String url) {
        String s = url.toLowerCase();
        return s.endsWith(".gif");
    }
}
